package display;

import javax.swing.*;
import java.awt.*;

/**
  * This program can run either as an applet or an application.
  * Both display an image on a JPanel object.
 **/
public class Test extends JApplet{
  static boolean fInBrowser = true;

  /** Create the applet interface by adding a DrawingPanel,
    * which will display an image.
   **/
  public void init ()  {
    Container content_pane = getContentPane ();

    // Grab the image with appropriate method.
    Image img;
    if (fInBrowser)
        img = getImage (getCodeBase (), "resource/graphics/lemming/walker/walker1.gif");
    else
        img = Toolkit.getDefaultToolkit ().getImage (
                                       "resource/graphics/lemming/walker/walker1.gif");

    // Create an instance of DrawingPanel
    DrawingPanel drawing_panel = new DrawingPanel (img);

    // Add the DrawingPanel to the content_pane.
    content_pane.add (drawing_panel);

  } // init

  /** For standalone mode, create a JFrame and add an instance
    * of this applet to it.
   **/
  public static void main (String[] args) {
    // Running as an application
    fInBrowser = false;
    // Create applet object
    JApplet applet = new Test ();

    // Create Frame
    JFrame f = new JFrame ("Frame/Applet Demo");
    f.setDefaultCloseOperation (JFrame.EXIT_ON_CLOSE);

    // Add applet to the frame
    f.getContentPane ().add (applet);
    f.setSize (new Dimension (350,250));

    // Initialize the applet
    applet.init ();
    f.setVisible (true);
  } // main

} // class FrameAppApplet

/** Draw on a JPanel rather than on JApplet's Panel. **/
class DrawingPanel extends JPanel
{
  Image fImg = null;

  DrawingPanel (Image img) {
    fImg = img;
  } // ctor

  /** Display an image. **/
  public void paintComponent (Graphics g) {
    // First paint background
    super.paintComponent (g);

    // Use the image width& width to find the starting point
    int img_x = getSize ().width/2  - fImg.getWidth (this)/2;
    int img_y = getSize ().height/2 - fImg.getHeight (this)/2;

    //Draw image at centered in the middle of the panel
    g.drawImage (fImg, img_x, img_y, this);

  } // paintComponent

} // class DrawingPanel